<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX GET 请求</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border: solid 1px #90b
        }
    </style>
</head>

<body>
    <button>点击发送请求</button>
    <div id="result"></div>
</body>
<script lang="javascript">
    const BASE_URL = "http://localhost:8000"
    // get button element
    const btn = document.getElementsByTagName("button")[0];
    const result = document.getElementById("result");
    // bind action to element
    btn.addEventListener("click", () => {
        // 1. create object 
        const xhr = new XMLHttpRequest();
        // 2. initialization set request method and url
        xhr.open('get', BASE_URL + '/server?a=100&b=200&c=300', true);
        // 3. send
        xhr.send()
        // 4. deal with response
        // readystate has 5 values 0 1 2 3 4
        // 0 init
        // 1 open 
        // 2 send
        // 3 server returns partial results
        // 4 server returns all results
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                if(xhr.status >= 200 && xhr.status < 300){
                    // handle result
                    // 1. response line
                    console.log(xhr.status);
                    console.log(xhr.statusText);
                    // 2. response header
                    console.log(xhr.getAllResponseHeaders());
                    // 3. response body
                    console.log(xhr.response);
                    // show response body in div 
                    result.innerHTML = xhr.response;
                }else{
                    
                }

            }
        }

    })
</script>

</html>